package com.cskaoyan.service.mall;

import com.cskaoyan.bean.mall.category.Category;
import com.cskaoyan.bean.mall.category.CategoryExample;
import com.cskaoyan.mapper.mall.CategoryMapper;
import com.cskaoyan.utils.Constant;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Repository
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Resource
    CategoryMapper categoryMapper;

    @Override
    public List<Category> queryCategory() {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andLevelEqualTo("L1");
        criteria.andDeletedEqualTo(false);
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        for (Category category : categoryList) {
            CategoryExample categoryExample1 = new CategoryExample();
            CategoryExample.Criteria criteria1 = categoryExample1.createCriteria();
            criteria1.andLevelEqualTo("L2");
            criteria1.andPidEqualTo(category.getId());
            criteria1.andDeletedEqualTo(false);
            category.setChildren(categoryMapper.selectByExample(categoryExample1));
        }
        return categoryList;
    }

    @Override
    public Category createCategory(Category category) {
        category.setAddTime(new Date());
        category.setUpdateTime(new Date());
        category.setSortOrder((byte) 1);
        int i = categoryMapper.insertSelective(category);
        if (i == 1) return category;
        return null;
    }

    //存在子目录不能删除
    //假如分类有商品存在，就把商品全删除，后面借用商品的mapper
    @Override
    public int deleteCategory(Category category) {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        criteria.andPidEqualTo(category.getId());
        criteria.andDeletedEqualTo(false);
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        if (categoryList.size() != 0) return Constant.FAIL;
        category.setDeleted(true);
        int i = categoryMapper.updateByPrimaryKeySelective(category);
        if (i == 1) return Constant.SUCCESS;
        return Constant.FAIL;
    }

    @Override
    public int updateCategory(Category category) {
        category.setUpdateTime(new Date());
        int i = categoryMapper.updateByPrimaryKeySelective(category);
        if (i == 1) return Constant.SUCCESS;
        return Constant.FAIL;
    }
}
